# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Run inference on images, videos, directories, streams, etc.

Usage - sources:
    $ python path/to/detect3.py --weights yolov5s.pt --source 0              # webcam
                                                             img.jpg        # image
                                                             vid.mp4        # video
                                                             path/          # directory
                                                             path/*.jpg     # glob
                                                             'https://youtu.be/Zgi9g1ksQHc'  # YouTube
                                                             'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP stream

Usage - formats:
    $ python path/to/detect3.py --weights yolov5s.pt                 # PyTorch
                                         yolov5s.torchscript        # TorchScript
                                         yolov5s.onnx               # ONNX Runtime or OpenCV DNN with --dnn
                                         yolov5s.xml                # OpenVINO
                                         yolov5s.engine             # TensorRT
                                         yolov5s.mlmodel            # CoreML (macOS-only)
                                         yolov5s_saved_model        # TensorFlow SavedModel
                                         yolov5s.pb                 # TensorFlow GraphDef
                                         yolov5s.tflite             # TensorFlow Lite
                                         yolov5s_edgetpu.tflite     # TensorFlow Edge TPU
"""

import argparse
import os
import platform
import sys
from pathlib import Path
from threading import Thread
from time import sleep
# import keyboard
import torch
import torch.backends.cudnn as cudnn

FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

from models.common import DetectMultiBackend
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
                           increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, time_sync
import requests
from requests.auth import HTTPDigestAuth
import time
from sklearn.cluster import DBSCAN
from numpy import genfromtxt
from numpy import transpose
from numpy import unique
import time
from numpy import where
from datetime import datetime
from PIL import ImageFont, ImageDraw, Image
from collections import Counter
import numpy
from math import cos, sin, atan2, sqrt, pi, radians, degrees

# 摄像头ip地址 用户名 密码
ip = '192.168.1.35'
admin = 'admin'
password = 'lyf188741'

rgb = [(0, 0, 0), (0, 255, 0), (0, 0, 255), (255, 0, 0), (255, 255, 255), (100, 100, 255),
       (255, 100, 100)]
dia = ['9mm', '5mm', '5mm', '5mm', '5mm', '5mm', '5mm', '5mm', '5mm']

global m1, hk, date_old, date_arrow, date_s, icons
m1 = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
m2 = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
hk = 1

a1 = ['A5', 'A4', 'B4', 'B3', 'C4', 'C3']
date_s = [0, 0, 0, 0, 0, 0]
icons = []


# class Attribute:


def preset_point(point):
    """预设点位"""
    session = requests.Session()
    url = 'http://%s/ISAPI/PTZCtrl/channels/1/presets/%d/goto' % (ip, point)
    session.put(url, auth=HTTPDigestAuth(admin, password))


# 计算中心点
def center_geolocation(geolocations):
    x = 0
    y = 0
    z = 0
    length = len(geolocations)
    for lon, lat in geolocations:
        lon = radians(float(lon))
        lat = radians(float(lat))
        x += cos(lat) * cos(lon)
        y += cos(lat) * sin(lon)
        z += sin(lat)

    x = float(x / length)
    y = float(y / length)
    z = float(z / length)

    return degrees(atan2(y, x)), degrees(atan2(z, sqrt(x * x + y * y)))


# 获取当前时间
def get_now_datetime():
    now = datetime.datetime.now()
    return str(now.strftime("%Y-%m-%d %H:%M:%S"))


def pattern(img, img_width, img_height, attrs):
    # 控制线的粗细
    pixel = 3
    for attr_key in attrs:
        attr = list(attrs[attr_key])
        xy_list = list(attr[2])
        color = attr[3]
        for xy in xy_list:
            x_centre = xy[0]
            y_centre = xy[1]
            i = 0
            while i < 5:
                img = cv2.rectangle(img,
                                    (int(x_centre * img_width) + i, int(y_centre * img_height) + i),
                                    (int(x_centre * img_width) + i, int(y_centre * img_height) + i),
                                    color, pixel)
                img = cv2.rectangle(img,
                                    (int(x_centre * img_width) - i, int(y_centre * img_height) - i),
                                    (int(x_centre * img_width) - i, int(y_centre * img_height) - i),
                                    color, pixel)
                img = cv2.rectangle(img,
                                    (int(x_centre * img_width) + i, int(y_centre * img_height) - i),
                                    (int(x_centre * img_width) + i, int(y_centre * img_height) - i),
                                    color, pixel)
                img = cv2.rectangle(img,
                                    (int(x_centre * img_width) - i, int(y_centre * img_height) + i),
                                    (int(x_centre * img_width) - i, int(y_centre * img_height) + i),
                                    color, pixel)
                i += 1
    return img


def drawing(a, img, myMap):
    global m1, date_old, hk, date_arrow, m2, date_s

    b_channel, g_channel, r_channel = cv2.split(img)
    alpha_channel = numpy.ones(b_channel.shape, dtype=b_channel.dtype) * 255
    img = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))

    d = numpy.array(a)
    if d.ndim != 2:
        return img
    dbscan = DBSCAN(eps=0.1, min_samples=5).fit(d)
    yhat = dbscan.labels_
    # unique 去重
    clusters = unique(yhat)
    img_width = img.shape[1]
    img_height = img.shape[0]

    lb = []
    zd1 = {}
    center = []
    map = {}
    for cluster in clusters:
        if cluster == -1:
            continue
        row_ix = where(yhat == cluster)
        mySum = 0
        myCount = 0
        data = []
        for row_ix_child in row_ix:
            for xy_index in row_ix_child:
                x_centre = d[xy_index, 0]
                y_centre = d[xy_index, 1]
                mykey = str(x_centre) + str(y_centre)
                myCount += 1
                mySum += myMap[mykey][0]
                xy = [x_centre, y_centre]
                data.append(xy)

        g = center_geolocation(data)
        one = [g, myCount, data]
        map[g[0]] = one
        center.append(g)
        lb.append(mySum / myCount)
        zd1[str(mySum / myCount)] = myCount

    new_map = dict(sorted(map.items(), key=lambda m: m[0], reverse=False))

    color_index = 0
    dia_index = 0
    for attr_key in new_map:
        color_index += 1
        attr = list(new_map[attr_key])
        attr.append(rgb[color_index])
        attr.append(dia[dia_index])
        new_map[attr_key] = attr
        dia_index += 1

    img = pattern(img, img_width, img_height, new_map)

    img_height, img_width = img.shape[:2]
    n_channels = 4
    transparent = numpy.zeros((img_height, img_width, n_channels), dtype=numpy.uint8)

    cv2.rectangle(transparent, (img_width - 550, 80), (img_width - 50, 500), (255, 255, 255), thickness=-1)
    img = cv2.addWeighted(img, 1, transparent, 0.7, 0)

    fontPath = "simsun.ttc"
    font = ImageFont.truetype(fontPath, 36)
    font_img = ImageFont.truetype(fontPath, 48)
    img_pil = Image.fromarray(img)

    draw = ImageDraw.Draw(img_pil)
    number = 0
    index = 0
    for attr_key in new_map:
        if attr_key >= 2:
            break
        attr = list(new_map[attr_key])
        # 直径
        diameter = attr[4]
        # 数量
        num = attr[1]
        number += num
        # 颜色
        # color = attr[3]

        # stringTxt = "直径 " + diameter + " 铝棒数量：" + str(num)

        # draw.text((img_width / 5 * 3, img_height - int(index) * 48 - 100),
        #           stringTxt, font=font,
        #           fill=color)
        b = (hk - 1) * 2 + index


        if ((datetime.now() - date_s[b]).seconds > 2) & (
                (abs(m1[int(b + 1)] - num) > 7) | (abs(m1[int(b + 1)] - num) < 3)):
            if m1[int(b + 1)] - num > 7:
                m2[int(b + 1)] = num - m1[int(b + 1)]
                date_arrow = datetime.now()
            elif m1[int(b + 1)] - num < -7:
                m2[int(b + 1)] = num - m1[int(b + 1)]
                date_arrow = datetime.now()
            m1[int(b + 1)] = num
            date_s[b] = datetime.now()

        index += 1
    date_now = datetime.now()
    for idx, m_key in enumerate(m1):
        print(idx,m_key)
        stringTxt = a1[idx] +  "铝棒数量：" + str(m1[m_key])   # "第" + str(m_key) +
        # # 绘制背景块
        # draw.rectangle((img_width - 170, m_key * 70 + 30 - 6, img_width - 70, (m_key + 1) * 70), fill=rgb[1],
        #                outline=rgb[1], width=1)
        # # 绘制上升箭头
        # mt = " ↑" + str(20)
        # draw.text((img_width - 200, m_key * 70 + 30 - 6),
        #           mt, font=font_img,
        #           fill=rgb[4])
        if m2[int(m_key)] != 0:
            if ((date_now - date_arrow).seconds < 4) & ((date_now - date_old).seconds > 7):
                m = m2[int(m_key)]
                if m > 0:
                    # 绘制背景块
                    draw.rectangle((img_width - 170, m_key * 70 + 30 - 6, img_width - 70, (m_key + 1) * 70),
                                   fill=rgb[2],
                                   outline=rgb[2], width=1)
                    # 绘制上升箭头
                    mt = " ↑" + str(m)
                    connect('4')
                    connect('4')
                    draw.text((img_width - 200, m_key * 70 + 30 - 6),
                              mt, font=font_img,
                              fill=rgb[4])
                else:
                    # 绘制背景块
                    draw.rectangle((img_width - 170, m_key * 70 + 30 - 6, img_width - 70, (m_key + 1) * 70),
                                   fill=(0, 200, 0),
                                   outline=(0, 200, 0), width=1)
                    # 绘制下降箭头
                    mt = " ↓" + str(abs(m))
                    connect('3')
                    draw.text((img_width - 200, m_key * 70 + 30 - 6),
                              mt, font=font_img,
                              fill=rgb[4])
            else:
                m2[int(m_key)] = 0
        draw.text((img_width - 500, m_key * 70 + 30),
                  stringTxt, font=font,
                  fill=rgb[0])
    icon = icons[hk - 1]
    icon_w, icon_h = icon.size

    for i in range(icon_w):
        for k in range(icon_h):
            color = icon.getpixel((i, k))
            color = color[:-1] + (200,)
            icon.putpixel((i, k), color)

    img_pil.paste(icon, (0, img_height - icon_h), mask=icon)

    # draw.text((img_width / 5 * 3, img_height - 50), "总数量：" + str(number), font=font, fill=(0, 255, 0))
    bk_img = numpy.array(img_pil)

    cv2.line(bk_img, (img_width - 550, 150), (img_width - 50, 150), (0, 0, 0), 3)
    cv2.line(bk_img, (img_width - 550, 220), (img_width - 50, 220), (0, 0, 0), 3)
    cv2.line(bk_img, (img_width - 550, 290), (img_width - 50, 290), (0, 0, 0), 3)
    cv2.line(bk_img, (img_width - 550, 360), (img_width - 50, 360), (0, 0, 0), 3)
    cv2.line(bk_img, (img_width - 550, 430), (img_width - 50, 430), (0, 0, 0), 3)
    cv2.rectangle(bk_img, (img_width - 550, 80), (img_width - 50, 500), (0, 0, 0), 3)

    return bk_img


@torch.no_grad()
def run(
        weights=ROOT / 'yolov5s.pt',  # model.pt path(s)
        source=ROOT / 'data/images',  # file/dir/URL/glob, 0 for webcam
        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path
        imgsz=(640, 640),  # inference size (height, width)
        conf_thres=0.25,  # confidence threshold
        iou_thres=0.45,  # NMS IOU threshold
        max_det=1000,  # maximum detections per image
        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu
        view_img=False,  # show results
        save_txt=True,  # save results to *.txt
        save_conf=True,  # save confidences in --save-txt labels
        save_crop=False,  # save cropped prediction boxes
        nosave=False,  # do not save images/videos
        classes=None,  # filter by class: --class 0, or --class 0 2 3
        agnostic_nms=False,  # class-agnostic NMS
        augment=False,  # augmented inference
        visualize=False,  # visualize features
        update=False,  # update all models
        project=ROOT / 'runs/detect',  # save results to project/name
        name='exp',  # save results to project/name
        exist_ok=False,  # existing project/name ok, do not increment
        line_thickness=3,  # bounding box thickness (pixels)
        hide_labels=False,  # hide labels
        hide_conf=False,  # hide confidences
        half=False,  # use FP16 half-precision inference
        dnn=False,  # use OpenCV DNN for ONNX inference
):
    global date_old, m2, hk, date_s, icons
    icon1 = Image.open("wz1.png")
    icon1 = icon1.convert("RGBA")
    icons.append(icon1)
    icon2 = Image.open("wz2.png")
    icon2 = icon2.convert("RGBA")
    icons.append(icon2)
    icon3 = Image.open("wz3.png")
    icon3 = icon3.convert("RGBA")
    icons.append(icon3)

    auto = True
    ind = 0
    while ind < 6:
        date_d = datetime.now()
        date_s[ind] = date_d
        ind += 1
    date_old = datetime.now()
    preset_point(1)
    source = str(source)
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
    webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
    if is_url and is_file:
        source = check_file(source)  # download

    # Directories
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir

    # Load model
    device = select_device(device)
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
    stride, names, pt = model.stride, model.names, model.pt
    imgsz = check_img_size(imgsz, s=stride)  # check image size

    # Dataloader
    if webcam:
        view_img = check_imshow()
        cudnn.benchmark = True  # set True to speed up constant image size inference
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
        bs = len(dataset)  # batch_size
    else:
        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
        bs = 1  # batch_size

    # Run inference
    model.warmup(imgsz=(1 if pt else bs, 3, *imgsz))  # warmup
    seen, windows, dt = 0, [], [0.0, 0.0, 0.0]
    bj = 0

    for path, im, im0s, vid_cap, s in dataset:
        date_now = datetime.now()
        if (date_now - date_old).seconds >= 30 and auto:
            m2 = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
            date_old = date_now
            if hk == 3:
                hk = 1
            else:
                hk += 1
            preset_point(hk)
            continue

        time_start = time.time()
        t1 = time_sync()
        im = torch.from_numpy(im).to(device)
        im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
        im /= 255  # 0 - 255 to 0.0 - 1.0
        if len(im.shape) == 3:
            im = im[None]  # expand for batch dim
        t2 = time_sync()
        dt[0] += t2 - t1

        # Inference
        visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
        pred = model(im, augment=augment, visualize=visualize)
        t3 = time_sync()
        dt[1] += t3 - t2

        # NMS
        pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
        dt[2] += time_sync() - t3

        for i, det in enumerate(pred):  # per image
            seen += 1
            if webcam:  # batch_size >= 1
                p, im0, frame = path[i], im0s[i].copy(), dataset.count
                s += f'{i}: '
            else:
                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)

            s += '%gx%g ' % im.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            myimg = im0.copy()
            d = []
            myMap = {}
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()

                # Print results
                for c in det[:, -1].unique():
                    n = (det[:, -1] == c).sum()  # detections per class
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                # Write results
                for *xyxy, conf, cls in reversed(det):
                    if save_txt:  # Write to file
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh

                        strxy = str(xywh[0]) + str(xywh[1])
                        mywh = [xywh[2], xywh[3]]
                        myMap[strxy] = mywh
                        d0 = [xywh[0], xywh[1]]
                        d.append(d0)
            aa = drawing(d, myimg, myMap)

            # cv2.imwrite("a2out.png", aa)
            cv2.namedWindow('test', cv2.WINDOW_NORMAL)
            cv2.imshow('test', aa)
            k = cv2.waitKey(1)
            # print(k)
            # print(ord('q'))
            # print(ord(k))
            # print(ord('1'))

            if k == ord('1'):
                hk = 1
                auto = False
                m2 = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
                date_old = date_now
                preset_point(hk)
            if k == ord('2'):
                hk = 2
                auto = False
                m2 = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
                date_old = date_now
                preset_point(hk)
            if k == ord('3'):
                hk = 3
                auto = False
                m2 = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
                date_old = date_now
                preset_point(hk)
            if k == ord('s'):
                auto = False
            if k == ord('0'):
                hk = 1
                auto = True
                m2 = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
                date_old = date_now
                preset_point(hk)

        # Print time (inference-only
        # time_end_down = time.time()
        # LOGGER.info(time_end_down - time_start)
        # LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')


def parse_opt():
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'best.pt', help='model path(s)')
    parser.add_argument('--source', type=str,
                        default='rtsp://admin:lyf188741@192.168.1.35:554/Streaming/Channels/101?transportmode=multicast',
                        # default=ROOT / 'a1.jpg',
                        help='file/dir/URL'
                             '/glob, '
                             '0 for webcam')
    parser.add_argument('--data', type=str, default=ROOT / 'data/aluminium.yaml', help='(optional) dataset.yaml path')
    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[2560],
                        help='inference size h,w')
    parser.add_argument('--conf-thres', type=float, default=0.5, help='confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
    parser.add_argument('--device', default='0', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    parser.add_argument('--view-img', action='store_true', help='show results')
    parser.add_argument('--save-txt', default=ROOT / 'txt', action='store_true', help='save results to *.txt')
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
    parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
    parser.add_argument('--augment', action='store_true', help='augmented inference')
    parser.add_argument('--visualize', action='store_true', help='visualize features')
    parser.add_argument('--update', action='store_true', help='update all models')
    parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
    parser.add_argument('--name', default='exp', help='save results to project/name')
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
    parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
    parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
    parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
    opt = parser.parse_args()
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
    print_args(vars(opt))
    return opt

def connect(message):
    import socket

    # 创建TCP/IP套接字
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 服务器地址和端口
    server_address = ('192.168.1.114', 6002)

    # 连接服务器
    client_socket.connect(server_address)

    try:
        # 发送数据
        client_socket.sendall(message.encode('utf-8'))

        # 接收响应
        # data = client_socket.recv(1024)
        # print(f"收到响应: {data.decode('utf-8')}")

    finally:
        # 关闭连接
        client_socket.close()

def main(opt):
    check_requirements(exclude=('tensorboard', 'thop'))
    return run(**vars(opt))


if __name__ == "__main__":
    opt = parse_opt()
    main(opt)
